package be.pluyckx.batteryprogress.components.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.Iterator;

import be.pluyckx.batteryprogress.R;
import be.pluyckx.batteryprogress.components.view.TitleBoxLayout;
import be.pluyckx.batteryprogress.data.history.snapshot.ProcessItem;
import be.pluyckx.batteryprogress.data.history.snapshot.ProcessSnapshot;
import be.pluyckx.batteryprogress.data.history.snapshot.ServiceItem;

/**
 * Created by Philip on 28/08/13.
 */
public class ProcessListAdapter extends BaseAdapter {
  private final LayoutInflater mInflater;
  private ProcessSnapshot mSnapshot;

  public ProcessListAdapter(Context context, ProcessSnapshot snapshot) {
    mInflater = LayoutInflater.from(context);
    mSnapshot = snapshot;
  }

  @Override
  public int getCount() {
    return (mSnapshot != null ? mSnapshot.count() : 0);
  }

  @Override
  public Object getItem(int i) {
    return (mSnapshot != null ? mSnapshot.get(i) : null);
  }

  @Override
  public long getItemId(int i) {
    return i;
  }

  @Override
  public View getView(int i, View view, ViewGroup viewGroup) {
    if (view == null) {
      view = mInflater.inflate(R.layout.view_process_listview_item, null, false);

      if (view != null) {
        ViewHolder holder = new ViewHolder();
        holder.tvProcessName = (TextView) view.findViewById(R.id.textview_process_name);
        holder.tvServiceNames = (TextView) view.findViewById(R.id.textview_servicename);
        holder.tblServices = (TitleBoxLayout) view.findViewById(R.id.titleboxlayout_services);
        view.setTag(holder);
      }
    }

    ViewHolder holder = (ViewHolder) view.getTag();
    ProcessItem item = (ProcessItem) getItem(i);

    if (item != null) {
      holder.tvProcessName.setText(item.toString(ProcessItem.FORMAT_PROCESS_NAME_PID));
      Iterator<ServiceItem> iterator = item.iterateServices();
      StringBuilder sb = new StringBuilder();
      if (iterator.hasNext()) {
        sb.append(iterator.next().getServiceName());
      } else {
        sb.append(view.getContext().getResources().getString(R.string.no_services));
      }
      while (iterator.hasNext()) {
        sb.append("\n");
        sb.append(iterator.next().getServiceName());
      }

      holder.tvServiceNames.setText(sb.toString());
    } else {
      holder.tvProcessName.setText(R.string.unknown);
      holder.tvServiceNames.setText(view.getContext().getResources().getString(R.string.no_services));
    }

    holder.tblServices.collapse();

    return view;
  }

  private static class ViewHolder {
    TextView tvProcessName;
    TextView tvServiceNames;
    TitleBoxLayout tblServices;
  }
}
